package com.kmxd.ams.app.event.es;

import com.kmxd.ams.app.arrange.command.EsCmd;
import com.kmxd.ams.client.event.es.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 索引数据到es监听
 *
 * @author nickbi
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "ams.search", name = "type", havingValue = "2")
public class EsIndexListener {

  private final EsCmd indexCmd;

  /**
   * 索引数据
   *
   * @param event 事件
   */
  @Async
  @TransactionalEventListener(fallbackExecution = true)
  public void save(EsSaveDataEvent event) {
    log.info("新建es数据监听，事件参数:{}", event);
    indexCmd.save(event.getIds(), event.getArchTypeId(), event.getTableId());
  }
  /**
   * 索引数据
   *
   * @param event 事件
   */
  @Async
  @TransactionalEventListener(fallbackExecution = true)
  public void update(EsUpdateDataEvent event) {
    log.info("更新es数据监听，事件参数:{}", event);
    indexCmd.update(event.getIds(), event.getArchTypeId(), event.getTableId());
  }

  /**
   * 索引数据
   *
   * @param event 事件
   */
  @Async
  @TransactionalEventListener(fallbackExecution = true)
  public void remove(EsRemoveDataEvent event) {
    log.info("删除es数据监听，事件参数:{}", event);
    indexCmd.removeByIds(event.getIds(), event.getTableId());
  }

  /**
   * 更新通用权限到es
   *
   * @param event 事件
   */
  @Async
  @TransactionalEventListener(fallbackExecution = true)
  public void updateAuth(EsUpdateAuthEvent event) {
    log.info("更新es权限信息监听，事件参数:{}", event);
    indexCmd.updateAuth(event.getArchTypeId());
  }

  @Async
  @TransactionalEventListener(fallbackExecution = true)
  public void createIndex(EsCreateIndexEvent event) {
    log.info("重建es索引监听，事件参数:{}", event);
    indexCmd.batchCreateIndex(event);
  }

  @Async
  @TransactionalEventListener(fallbackExecution = true)
  public void removeCollectionAgainData(RemoveEsDataEvent event) {
    log.info("删除重新整理es数据监听，事件参数:{}", event);
    indexCmd.removeData(event);
  }
}
